import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/account_provider.dart';
import '../providers/show_provider.dart';
import '../providers/ticket_hunter_provider.dart';
import '../models/platform_config.dart';
import '../models/show.dart';
import '../utils/logger.dart';
import 'account_management_screen.dart';
import 'show_config_screen.dart';
import 'platform_selection_screen.dart';
import 'unified_hunting_screen.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
    _initializeData();
  }

  Future<void> _initializeData() async {
    try {
      await context.read<AccountProvider>().loadAccounts();
      await context.read<ShowProvider>().loadShows();
    } catch (e) {
      AppLogger.error('Failed to initialize data', e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('抢票利器'),
        backgroundColor: Colors.red[600],
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.swap_horiz),
            onPressed: () => _showPlatformSelection(context),
            tooltip: '切换平台',
          ),
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () => _showSettingsMenu(context),
          ),
        ],
      ),
      body: Column(
        children: [
          _buildStatusCard(),
          _buildQuickActions(),
          Expanded(child: _buildShowList()),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _navigateToShowConfig(),
        backgroundColor: Colors.red[600],
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  Widget _buildStatusCard() {
    return Consumer2<TicketHunterProvider, ShowProvider>(
      builder: (context, huntingProvider, showProvider, child) {
        final selectedPlatform = showProvider.selectedPlatform ?? TicketPlatform.damai;
        final platformConfig = PlatformConfig.getConfig(selectedPlatform);
        
        return Container(
          margin: const EdgeInsets.all(16),
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                _getPlatformColor(selectedPlatform).withOpacity(0.8),
                _getPlatformColor(selectedPlatform),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: _getPlatformColor(selectedPlatform).withOpacity(0.3),
                blurRadius: 10,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text(
                        platformConfig.platformIcon,
                        style: const TextStyle(fontSize: 24),
                      ),
                      const SizedBox(width: 8),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            '当前平台',
                            style: TextStyle(
                              color: Colors.white70,
                              fontSize: 12,
                            ),
                          ),
                          Text(
                            platformConfig.platformName,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: _getStatusColor(huntingProvider.status),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Text(
                      _getStatusText(huntingProvider.status),
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: _buildStatusItem(
                      '活跃演出',
                      showProvider.activeShows.length.toString(),
                      Icons.event,
                    ),
                  ),
                  Expanded(
                    child: _buildStatusItem(
                      '成功次数',
                      huntingProvider.successCount.toString(),
                      Icons.check_circle_outline,
                    ),
                  ),
                  Expanded(
                    child: _buildStatusItem(
                      '失败次数',
                      huntingProvider.errorCount.toString(),
                      Icons.error_outline,
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildStatusItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.white70, size: 24),
        const SizedBox(height: 8),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          label,
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  Widget _buildQuickActions() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        children: [
          // 平台选择按钮
          Consumer<ShowProvider>(
            builder: (context, showProvider, child) {
              return Card(
                child: InkWell(
                  onTap: () => _showPlatformSelection(context),
                  borderRadius: BorderRadius.circular(12),
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Row(
                      children: [
                        Icon(Icons.swap_horiz, color: Colors.blue[600]),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                '选择抢票平台',
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                ),
                              ),
                              Text(
                                '当前: ${showProvider.selectedPlatform != null ? PlatformConfig.getConfig(showProvider.selectedPlatform!).platformName : '未选择'}',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Icon(Icons.arrow_forward_ios, color: Colors.grey[400], size: 16),
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
          const SizedBox(height: 12),
          // 功能按钮
          Row(
            children: [
              Expanded(
                child: _buildActionButton(
                  '账号管理',
                  Icons.account_circle,
                  Colors.blue,
                  () => _navigateToAccountManagement(),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildActionButton(
                  '演出配置',
                  Icons.event,
                  Colors.green,
                  () => _navigateToShowConfig(),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildActionButton(
                  '开始抢票',
                  Icons.flash_on,
                  Colors.orange,
                  () => _navigateToHunting(),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildActionButton(
    String label,
    IconData icon,
    Color color,
    VoidCallback onPressed,
  ) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: color,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(vertical: 16),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        elevation: 2,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 24),
          const SizedBox(height: 4),
          Text(
            label,
            style: const TextStyle(fontSize: 12),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildShowList() {
    return Consumer<ShowProvider>(
      builder: (context, provider, child) {
        final shows = provider.activeShows;
        
        if (shows.isEmpty) {
          return _buildEmptyState();
        }

        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: shows.length,
          itemBuilder: (context, index) {
            final show = shows[index];
            return _buildShowCard(show);
          },
        );
      },
    );
  }

  Widget _buildEmptyState() {
    return Consumer<ShowProvider>(
      builder: (context, showProvider, child) {
        final selectedPlatform = showProvider.selectedPlatform;
        final platformConfig = selectedPlatform != null 
            ? PlatformConfig.getConfig(selectedPlatform)
            : null;
            
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                selectedPlatform == null ? Icons.platform_outlined : Icons.event_busy,
                size: 80,
                color: Colors.grey[400],
              ),
              const SizedBox(height: 16),
              Text(
                selectedPlatform == null ? '请先选择抢票平台' : '暂无演出配置',
                style: TextStyle(
                  fontSize: 18,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                selectedPlatform == null 
                    ? '点击上方"选择抢票平台"开始使用'
                    : '点击右下角按钮添加${platformConfig?.platformName}演出',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[500],
                ),
              ),
              if (selectedPlatform == null) ...[
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () => _showPlatformSelection(context),
                  child: const Text('选择平台'),
                ),
              ],
            ],
          ),
        );
      },
    );
  }

  Widget _buildShowCard(Show show) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 4,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        onTap: () => _navigateToShowDetail(show),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    show.platformIcon,
                    style: const TextStyle(fontSize: 20),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      show.name,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: show.isEnabled ? Colors.green : Colors.grey,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      show.isEnabled ? '启用' : '禁用',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                '地点: ${show.venue}',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 4),
              Text(
                '票档: ${show.skus.length} 个',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 12),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: _getPlatformColor(show.platform).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      show.platformName,
                      style: TextStyle(
                        color: _getPlatformColor(show.platform),
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  Row(
                    children: [
                      IconButton(
                        icon: Icon(
                          show.isEnabled ? Icons.pause : Icons.play_arrow,
                          color: show.isEnabled ? Colors.orange : Colors.green,
                        ),
                        onPressed: () => _toggleShow(show),
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                      ),
                      const SizedBox(width: 8),
                      IconButton(
                        icon: const Icon(Icons.edit, color: Colors.blue),
                        onPressed: () => _editShow(show),
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                      ),
                      const SizedBox(width: 8),
                      IconButton(
                        icon: const Icon(Icons.delete, color: Colors.red),
                        onPressed: () => _deleteShow(show),
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color _getPlatformColor(TicketPlatform platform) {
    switch (platform) {
      case TicketPlatform.damai:
        return Colors.red;
      case TicketPlatform.maoyan:
        return Colors.orange;
    }
  }

  Color _getStatusColor(TicketHunterStatus status) {
    switch (status) {
      case TicketHunterStatus.idle:
        return Colors.grey;
      case TicketHunterStatus.running:
        return Colors.green;
      case TicketHunterStatus.paused:
        return Colors.orange;
      case TicketHunterStatus.error:
        return Colors.red;
    }
  }

  String _getStatusText(TicketHunterStatus status) {
    switch (status) {
      case TicketHunterStatus.idle:
        return '空闲';
      case TicketHunterStatus.running:
        return '运行中';
      case TicketHunterStatus.paused:
        return '已暂停';
      case TicketHunterStatus.error:
        return '错误';
    }
  }

  void _showPlatformSelection(BuildContext context) async {
    final selectedPlatform = await Navigator.push<TicketPlatform>(
      context,
      MaterialPageRoute(
        builder: (context) => const PlatformSelectionScreen(),
      ),
    );
    
    if (selectedPlatform != null) {
      context.read<ShowProvider>().setSelectedPlatform(selectedPlatform);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('已切换到${PlatformConfig.getConfig(selectedPlatform).platformName}'),
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

  void _showSettingsMenu(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.swap_horiz),
              title: const Text('切换平台'),
              onTap: () {
                Navigator.pop(context);
                _showPlatformSelection(context);
              },
            ),
            ListTile(
              leading: const Icon(Icons.account_circle),
              title: const Text('账号管理'),
              onTap: () {
                Navigator.pop(context);
                _navigateToAccountManagement();
              },
            ),
            ListTile(
              leading: const Icon(Icons.settings),
              title: const Text('应用设置'),
              onTap: () {
                Navigator.pop(context);
                // TODO: 导航到设置页面
              },
            ),
            ListTile(
              leading: const Icon(Icons.info),
              title: const Text('关于应用'),
              onTap: () {
                Navigator.pop(context);
                _showAboutDialog();
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showAboutDialog() {
    showAboutDialog(
      context: context,
      applicationName: '抢票利器',
      applicationVersion: '2.1.0',
      applicationIcon: const Icon(Icons.flash_on, size: 48),
      children: [
        const Text('专业的多平台抢票工具'),
        const SizedBox(height: 16),
        const Text('支持平台:'),
        const Text('• 大麦网 - 演唱会、话剧、体育赛事'),
        const Text('• 猫眼电影 - 电影票、演出票'),
        const SizedBox(height: 16),
        const Text('功能特性:'),
        const Text('• 多平台统一管理'),
        const Text('• 智能抢票算法'),
        const Text('• 实时状态监控'),
        const Text('• 批量抢票支持'),
      ],
    );
  }

  void _navigateToAccountManagement() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const AccountManagementScreen()),
    );
  }

  void _navigateToShowConfig() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const ShowConfigScreen()),
    );
  }

  void _navigateToHunting() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const UnifiedHuntingScreen()),
    );
  }

  void _navigateToShowDetail(Show show) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ShowConfigScreen(show: show),
      ),
    );
  }

  void _editShow(Show show) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ShowConfigScreen(show: show),
      ),
    );
  }

  void _toggleShow(Show show) {
    context.read<ShowProvider>().toggleShow(show.id);
  }

  void _deleteShow(Show show) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除演出 "${show.name}" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              context.read<ShowProvider>().removeShow(show.id);
              Navigator.pop(context);
            },
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}